package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.SeckillVoucher;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IVoucherService;
import com.hmdp.utils.RedisCreateId;
import com.hmdp.utils.RedisSimpleLock;
import com.hmdp.utils.UserHolder;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.stream.*;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Service
@RequiredArgsConstructor
@Slf4j
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    private final ISeckillVoucherService seckillVoucherService;
    private final RedisCreateId redisCreateId;
    private final RedissonClient redissonClient;
    private final StringRedisTemplate stringRedisTemplate;
    private static final DefaultRedisScript<Long> SECKILL_SCRIPT;

    static {
        SECKILL_SCRIPT = new DefaultRedisScript<>();
        SECKILL_SCRIPT.setLocation(new ClassPathResource("seckill.lua"));
        SECKILL_SCRIPT.setResultType(Long.class);
    }

    private BlockingQueue<VoucherOrder> orderTasks = new ArrayBlockingQueue<>(1024 * 1024);
    private final ExecutorService SECKILL_ORDER_EXECUTOR = Executors.newSingleThreadExecutor();

    @PostConstruct
    public void init() {
        SECKILL_ORDER_EXECUTOR.submit(new VoucherOrderHandler());
    }

    private class VoucherOrderHandler implements Runnable {
        String queueName = "stream.orders";

        @Override
        //Stream消息队列实现
        public void run() {
            while (true) {
                try {
                    List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(
                            Consumer.from("g1", "c1"),
                            StreamReadOptions.empty().count(1).block(Duration.ofSeconds(2)),
                            StreamOffset.create(queueName, ReadOffset.lastConsumed())
                    );
                    if (list == null || list.isEmpty()) {
                        continue;
                    }
                    MapRecord<String, Object, Object> record = list.get(0);
                    Map<Object, Object> map = record.getValue();
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(map, new VoucherOrder(), true);
                    handleOrder(voucherOrder);
                    stringRedisTemplate.opsForStream().acknowledge(queueName, "g1", record.getId());
                } catch (Exception e) {
                    handlePendingList();
                }
            }
        }
    }

    private void handlePendingList() {
        String queueName = "stream.orders";
        while (true) {
            try {
                List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(
                        Consumer.from("g1", "c1"),
                        StreamReadOptions.empty().count(1),
                        StreamOffset.create(queueName, ReadOffset.from("0"))
                );
                if (list == null || list.isEmpty()) {
                    break;
                }
                MapRecord<String, Object, Object> record = list.get(0);
                Map<Object, Object> map = record.getValue();
                VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(map, new VoucherOrder(), true);
                handleOrder(voucherOrder);
                stringRedisTemplate.opsForStream().acknowledge(queueName, "g1", record.getId());
            } catch (Exception e) {
                log.error("订单处理异常",e);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException ex) {
                    throw new RuntimeException(ex);
                }
            }
        }
    }
//    private class VoucherOrderHandler implements Runnable {
//        @Override
//        public void run() {
//            while (true) {
//                try {
//                    VoucherOrder voucherOrder = orderTasks.take();
//                    handleOrder(voucherOrder);
//                } catch (InterruptedException e) {
//                    log.error("订单处理异常");
//                }
//            }
//        }
//    }

        private IVoucherOrderService proxy;

        private void handleOrder (VoucherOrder voucherOrder){
            Long userId = voucherOrder.getUserId();
            RLock lock = redissonClient.getLock("lock:order:" + userId);
            boolean b = lock.tryLock();
            if (!b) {
                log.error("不允许重复下单");
                return;
            }
            try {
                proxy.makeOrder(voucherOrder);
            } finally {
                lock.unlock();
            }
        }
        @Override
        public Result seckillVoucher (Long voucherId){
            SeckillVoucher seckillVoucher = seckillVoucherService.getById(voucherId);
            //判断秒杀是否开始或结束
            if (seckillVoucher.getBeginTime().isAfter(LocalDateTime.now())) {
                return Result.fail("活动未开始");
            }
            if (seckillVoucher.getEndTime().isBefore(LocalDateTime.now())) {
                return Result.fail("活动已结束");
            }
            //1 执行lua脚本，判断是否有购买资格
            Long userId = UserHolder.getUser().getId();
            long orderId = redisCreateId.nextId("voucher_order");
            Long result = stringRedisTemplate.execute
                    (SECKILL_SCRIPT, Collections.emptyList(), voucherId.toString(), userId.toString(),
                            String.valueOf(orderId));
            //2.1 结果为1或2：无购买资格，返回错误信息
            int r = result.intValue();
            if (r != 0) {
                return Result.fail(r == 1 ? "抢购失败，库存不足" : "抢购失败，一人只能抢购一单");
            }
            //2.2 结果为0：有购买资格
            proxy = (IVoucherOrderService) AopContext.currentProxy();
            //3 返回订单id
            return Result.ok(orderId);
        }
//    @Override
//    public Result seckillVoucher(Long voucherId) {
//        SeckillVoucher seckillVoucher = seckillVoucherService.getById(voucherId);
//        //判断秒杀是否开始或结束
//        if (seckillVoucher.getBeginTime().isAfter(LocalDateTime.now())) {
//            return Result.fail("活动未开始");
//        }
//        if (seckillVoucher.getEndTime().isBefore(LocalDateTime.now())) {
//            return Result.fail("活动已结束");
//        }
//        //1 执行lua脚本，判断是否有购买资格
//        Long userId = UserHolder.getUser().getId();
//        Long result = stringRedisTemplate.execute
//                (SECKILL_SCRIPT, Collections.emptyList(), voucherId.toString(), userId.toString());
//        //2.1 结果为1或2：无购买资格，返回错误信息
//        int r = result.intValue();
//        if (r != 0) {
//            return Result.fail(r == 1 ? "抢购失败，库存不足" : "抢购失败，一人只能抢购一单");
//        }
//        //2.2 结果为0：有购买资格,将下单信息保存到阻塞队列中
//        VoucherOrder voucherOrder = new VoucherOrder();
//        voucherOrder.setVoucherId(voucherId);
//        voucherOrder.setUserId(UserHolder.getUser().getId());
//        long orderId = redisCreateId.nextId("voucher_order");
//        voucherOrder.setId(orderId);
//        orderTasks.add(voucherOrder);
//        proxy = (IVoucherOrderService) AopContext.currentProxy();
//        //3 返回订单id
//        return Result.ok(orderId);
//    }


        //    public Result seckillVoucher(Long voucherId) {
//        //1.查询优惠劵
//        SeckillVoucher seckillVoucher = seckillVoucherService.getById(voucherId);
//        //2.判断秒杀是否开始或结束
//        if (seckillVoucher.getBeginTime().isAfter(LocalDateTime.now())) {
//            return Result.fail("活动未开始");
//        }
//        if (seckillVoucher.getEndTime().isBefore(LocalDateTime.now())) {
//            return Result.fail("活动已结束");
//        }
//        //3.判断库存是否充足
//        if (seckillVoucher.getStock() < 1) {
//            return Result.fail("库存不足");
//        }
//        Long userId = UserHolder.getUser().getId();
//        synchronized (userId.toString().intern()) {
//            IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
//            return proxy.makeOrder(voucherId);
//        }
//
//        RedisSimpleLock lock = new RedisSimpleLock("order:" + userId, stringRedisTemplate);
//        boolean b = lock.tryLock(12000);
//        if(!b){
//            return Result.fail("抢购失败，请稍后再试");
//        }
//        try {
//            IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
//            return proxy.makeOrder(voucherId);
//        } finally {
//            lock.unlock();
//        }
//        return makeOrder(voucherId);
//    }
//
        @Transactional
        public void makeOrder (VoucherOrder voucherOrder){
            //4.判断用户是否购买过
            Long count = query().eq("voucher_id", voucherOrder.getVoucherId())
                    .eq("user_id", voucherOrder.getUserId()).count();
            if (count > 0) {
                log.error("不允许重复购买");
            }
            //5.扣减库存
            boolean flag = seckillVoucherService
                    .update()
                    .setSql("stock=stock-1")
                    .eq("voucher_id", voucherOrder.getVoucherId())
                    .gt("stock", 0)
                    .update();
            if (!flag) {
                log.error("扣减库存失败");
            }
            //6.生成订单
            save(voucherOrder);
        }
    }

